package keter.security.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import keter.framework.web.util.RequestUtil;
import keter.security.UserAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class SuccessHandler implements AuthenticationSuccessHandler {
	/**
	* Logger for this class
	*/
	private static final Logger logger = LoggerFactory.getLogger(SuccessHandler.class);
	
    public SuccessHandler() {
    }
 
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
    	if(!RequestUtil.isAjax(request)){
    		response.sendRedirect("/loginsuccess"); 
    	}
		//清除登录异常信息
		clearAuthenticationAttributes(request);
        UserAdapter ua = (UserAdapter)authentication.getPrincipal();
        //创建一个用于前台显示基本个人信息的安全用户
        response.setCharacterEncoding("UTF-8");  
        response.setContentType("application/json; charset=utf-8");  
        PrintWriter out = null;  
        try {  
            out = response.getWriter();  
            out.append(ua.getUser().getSecuredInfo().toJson());  
        } catch (IOException e) {  
        	logger.error("向前台返回user对象失败",e);
        } finally {  
            if (out != null) {  
                out.close();  
            }  
        }  
    }
    
	/**
	 * Removes temporary authentication-related data which may have been stored in the
	 * session during the authentication process.
	 */
	protected final void clearAuthenticationAttributes(HttpServletRequest request) {
		HttpSession session = request.getSession(false);

		if (session == null) {
			return;
		}

		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}
}